<template>
	<view>
		<image mode="widthFix" src="../../static/img/bianzhu.png" class="img_background"></image>
		<view class="header">
			<view>您好,</view>
			<view>欢迎使用{{oaconfig.corporateName}}</view>
		</view>
		<view
			class="ly-nowrap main-logo"
			style="
        width: 100%;
        height: 450upx;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
			:style="{ backgroundColor: oaconfig.backgroundColor }"
		>
		</view>
		<view class="login-wrapper">
			<view class="main" style="box-shadow: 1px 1px 6px 3px rgb(0 10 47 / 3%);">
                <view class="main-login-title" style="background: linear-gradient(to bottom, #F5F5F5 0%, #F5F5F5 50%, #fff 0%, #fff 0%);">
                    <view class="login-title-left" @click="switchTitle=false" :class="switchTitle ? 'title-left-f' : 'title-left-t'">
                        <text>账号密码登录</text>
                        </view>
                    <!-- <view class="login-title-right" @click="switchTitle=true" :class="switchTitle ? 'title-right-f' : 'title-right-t'">
                        <text>手机验证码登录</text>
                    </view> -->
                </view>
				<form class="loginView" @submit="bindLogin" v-if="!switchTitle">
					<view class="input-view">
						<input
							class="input"
							:value="username"
							@input="changeUsername"
							type="text"
							placeholder="请输入用户名"
							name="username"
							@focus="focusFun('1')"
							@blur="blurFun"
						/>
						<text class="iconfont icon-guanbi" v-if="username.length > 0 && focusType == '1'" @tap="clear('username')" style="line-height: 50upx;"></text>
					</view>
					<view class="input-view">
						<input
							class="input"
							:value="password"
							@input="changePwd"
							:type="passwordtype"
							placeholder="请输入密码"
							name="password"
							@focus="focusFun('2')"
							@blur="blurFun"
						/>
						<!-- @tap="clear('password')" -->
						<text
							class="iconfont icon-yanjing"
							v-if="password.length > 0 && focusType == '2'"
							style=" line-height: 50upx;padding-left: 10upx;"
							@tap="toviewpassword"
						></text>
					</view>
					<view style="display: flex; min-height: 100upx; align-items: center;">
						<checkbox-group @change="remember_change" class="remember remember1" style="flex: 5;">
							<label style="color: #666666">
								<checkbox class="remember_box" value="remember_box" :checked="remember_box" style="transform:scale(0.7)" />
								记住密码
							</label>
						</checkbox-group>
						<!-- <checkbox-group class="remember" style="flex: 5;">
							<label style="color: #666666">
								<text @tap="toresetPwdByEmail">找回密码</text>
							</label>
						</checkbox-group> -->
					</view>
					<!-- <view class="protocol" @click="protocol=!protocol">
            <label style="color: #666666">
                <view class="select" :class="protocol?'selectb':''"></view>
                <text>我已阅读并同意《用户服务协议及隐私政策》</text>
            </label>
          </view> -->
					<view class="button-view">
						<button
							:loading="loading"
							class="loginBtn"
							:class="isOk ? '' : 'opacity_05'"
							type="primary"
							formType="submit"
							:style="{ backgroundColor: oaconfig.backgroundColor }"
						>
							登 录
						</button>
					</view>
				</form>
                <form class="loginView" @submit="bindLogin2" v-if="switchTitle">
                    <view class="input-view">
                        <input
                            class="input"
                            v-model="mobile"
                            type="number"
                            placeholder="请输入手机号"
                            name="mobile"
                            maxlength="11"
                        />
                        <text class="iconfont icon-guanbi" @tap="mobile=''" style="line-height: 50upx;"></text>
                    </view>
                    <view class="input-view">
                        <input
                            class="input"
                            style="width: 50%;"
                            v-model="verificationCode"
                            type="text"
                            placeholder="请输入短信验证码"
                            name="verificationCode"
                            :maxlength="6"
                        />
                      <view style="width: 1px;height: 20px;margin: 13px 14px 0;background-color: #888;"></view>
                      <view
                        class="sendCode"
                        style="display: flex;align-items: center;justify-content: center;font-size: 13px;padding-right: 10px;width: 200upx;"
                        :style="{ color: getCodeNum == 0?oaconfig.backgroundColor:'#ccc' }"
                        @tap="getsendCode"
                        >{{getCode}}<text v-show="getCodeNum > 0">({{getCodeNum}}s)</text></view>
                    </view>
                    <view class="button-view" style="margin-top: 30px;">
                        <button
                            :loading="loading"
                            class="loginBtn"
                            :class="isOk2 ? '' : 'opacity_05'"
                            type="primary"
                            formType="submit"
                            :style="{ backgroundColor: oaconfig.backgroundColor }"
                        >
                            登 录
                        </button>
                    </view>
                </form>
			</view>
		</view>
	</view>
</template>

<script>
var _self;
import { validlogin, gettwotokenBPMtoken} from '@/workspaces/api/framework/service.js';
import $api from '@/workspaces/api/framework/api.js';
import MD5 from 'js-md5';

export default {
	data() {
		return {
			username: '',
			password: '',
			validCode: '',
			validCodeId: '',
			validImg: '',
			loading: false,
			oaconfig: {},
			remember_box: false,
			protocol: true,
			focusType: '0', //当前聚焦
			passwordtype: 'password',
            switchTitle: false,
            getCode: '获取验证码',
            mobile: '',
            verificationCode: '',
            Interval: '',
            getCodeNum: 0
		};
	},

	onLoad(e) {
		let _self = this;
		this.oaconfig = this.$oaconfig;
		this.isSubmit = false; // 防止多次点击
        uni.setNavigationBarTitle({
        	title: _self.$oaconfig.corporateName
        });
	},
	onShow() {
        let _self = this;
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: this.$oaconfig.backgroundColor
		});
        uni.setNavigationBarTitle({
        	title: _self.$oaconfig.corporateName
        });
		var remember_key = uni.getStorageSync('remember_key');
		if (remember_key) {
			remember_key = JSON.parse(this.$api.decrypt(remember_key));
			this.username = remember_key.username;
			this.password = remember_key.password;
			this.remember_box = true;
		}
	},
	methods: {
		toresetPwdByEmail(){
			uni.navigateTo({
				url: './resetPwdByEmail'
			});
		},
		toviewpassword() {
			if (this.passwordtype == 'password') {
				this.passwordtype = 'text';
			} else {
				this.passwordtype = 'password';
			}
		},
		focusFun(number) {
			setTimeout(() => {
				this.focusType = number;
			});
		},
		blurFun() {
			setTimeout(() => {
				this.focusType = 0;
			});
			// this.passwordtype = 'password'
		},
		//记住密码
		remember_change(e) {
			var remember_box = e.detail.value[0];
			if (remember_box == 'remember_box') {
				this.remember_box = true;
			} else {
				this.remember_box = false;
			}
		},
		remember(requestObj) {
			try {
				let storageObject = {};

				Object.keys(requestObj).forEach(key => {
					storageObject[key] = $api.aesEncrypt(requestObj[key]);
				});

				uni.setStorageSync('FRAMEWORK_USER_LOGIN_INFO', storageObject);
			} catch (e) {
				this.clearStatus();
				console.error('remember():::', e);
			}
		},

		// 这里通过：value去绑定数据，是为了避免直接用v-model在低版本的Hbuilder中抖动，数据不正确的情况
		changeUsername(e) {
			this.username = e.detail.value;
			this.password = '';
		},

		changePwd(e) {
			this.password = e.detail.value;
		},

		clear(key) {
			let storageObject = uni.getStorageSync('FRAMEWORK_USER_LOGIN_INFO');

			this[key] = '';

			if (storageObject) {
				delete storageObject[key];
			}

			if (key == 'username') {
				this.password = '';
				if (storageObject) {
					delete storageObject['password'];
				}
			}
            if (key == 'password') {
            	this.password = '';
            	if (storageObject) {
            		delete storageObject['password'];
            	}
            }

			uni.setStorageSync('FRAMEWORK_USER_LOGIN_INFO', storageObject);
		},

		prevent(e) {
			if (e.preventDefault) {
				e.preventDefault();
			}

			if (e.stopPropagation) {
				e.stopPropagation();
			}
		},

		clearStatus() {
			this.loading = false;
			this.isSubmit = false;
		},
		validParam(username, password, validCode) {
			if (this.isSubmit) {
				return false;
			}
			if (username.length === 0) {
				$api.showTip("请输入用户名");
				return false;
			}

			if (password.length === 0) {
				$api.showTip("请输入密码");
				return false;
			}
			return true;
		},

		password2Md5(password, username, randomCode) {
			function md(str) {
				return MD5(str).toLowerCase();
			}

			return md(md(md(md(md(username + md(md(md(password))))))) + randomCode);
		},

		bindLogin(e) {
			if (!this.protocol) {
				$api.showModalWithCloseButton('请同意《用户服务协议及隐私政策》后重试');
				return;
			}
			var than = this;
			const username = e.detail.value.username,
				password = e.detail.value.password,
				validCode = e.detail.value.validCode,
				randomCode = Math.random()
					.toString()
					.substring(2);

			if (!this.validParam(username, password, validCode)) return;

			const md5Password = this.password2Md5(this.getPassword(password), username, randomCode);
			//支持MP2.4版本登录   获取本地地址拼接 到登录参数   wxx  2020/09/10
			if (!window.location.origin) {
				window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
			}

			const params = {
				user: username,
				pwd: md5Password,
				lang: 'zh-CN',
				clientid: this.validCodeId,
				vcode: validCode,
				mode: '0',
				randomCode: randomCode
			};

			this.loading = true;
			this.isSubmit = true;
			validlogin({
				reuestParas: $api.aesEncrypt(JSON.stringify(params), 'mplanyou07558888'),
				token: '',
				ClientServer: window.location.origin //支持MP2.4版本登录   获取本地地址拼接 到登录参数   wxx  2020/09/10
			}).then(result => {
				if (result.success) {
					// console.log("登录信息："+result)
					// 登陆成功之后，缓存用户信息，跳转到审批页面
					result.data.ly_id = result.data.userid;
					result.data.ly_loginname = result.data.username;
					$api.setUserInfo(result.data);
					gettwotokenBPMtoken({
						tenancyId: 'BPM',
						mptoken: result.data.token
					}).then(res => {
						if (res.success) {
							result.data.token= res.data.token;
							if (than.remember_box) {
								var ase = $api.aesEncrypt(JSON.stringify(e.detail.value), 'mplanyou07558888');
								uni.setStorageSync('remember_key', ase);
							} else {
								uni.removeStorageSync('remember_key');
							}
							than.$store.commit('user', result.data)
							than.$store.commit('loginauthor', result.data)
							uni.setStorageSync('login_type', 'local')
							uni.reLaunch({
								url: '../index/index'
							});
						}else{
							than.$store.commit('logout');
							than.clearStatus();
							than.handleLoginUnSuccess(result, username);
						}
					}).catch(e => {
						than.clearStatus();
						$api.showModalWithCloseButton(e.message);
					});
				} else {
					than.clearStatus();
					than.handleLoginUnSuccess(result, username);
				}
			}).catch(e => {
				than.clearStatus();
				$api.showModalWithCloseButton(e.message);
			});
		},
        bindLogin2(){
            let _this = this;
            if (this.mobile.length != 11) {
              $api.showTip("请输入11位手机号");
              return;
            }
            var reg_tel = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;    //11位手机号码正则
            if(!reg_tel.test(this.mobile)){
                $api.showTip("请输入正确的手机号");
              return;
            }
            if (this.verificationCode.length != 6) {
              $api.showTip("请输入6位短信验证码");
              return;
            }
            uni.setStorageSync('mobile_key', this.mobile);
            // 短信登录
            _this.$lyRequest.post("/ly/mp/busicen/cm/basedata/sysUser/loginOnByMobileCode", {
              mobile: this.mobile,
              verificationCode: this.verificationCode
            },'form').then(result=>{
              if(result.data && result.data.result == 1){
                result.data.ly_id = result.data.rows.userid;
                result.data.ly_loginname = result.data.rows.username;
                _this.$api.setUserInfo(result.data.rows);
                setTimeout(() => {
                	uni.switchTab({
                		url: '/pages/oa/index/index'
                	});
                }, 10);
              }else{
                _this.$api.showTip(result.data.msg);
              }
            });
        },
        getsendCode(){
            let _this = this;
            if(this.getCode!='获取验证码'){
              $api.showTip("请在倒计时后重试");
              return;
            }
            if (this.mobile.length != 11) {
              $api.showTip("请输入11位手机号");
              return;
            }
            var reg_tel = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;    //11位手机号码正则
            if(!reg_tel.test(this.mobile)){
                $api.showTip("请输入正确的手机号");
              return;
            }
            // 短信接口
            this.$lyRequest.get("/ly/mp/busicen/cm/basedata/sysUser/loginOnByMobile", {
              mobile: this.mobile,
            }).then(result=>{
              if(result.data && result.data.result == 1){
                _this.getCode = '请稍后';
                _this.$api.showTip('短信发送成功');
                // 60秒倒计时
                _this.getCodeNum = 60
                _this.Interval = setInterval(() => {
                    if(_this.getCodeNum > 0){
                        _this.getCodeNum--;
                    }else if(_this.getCodeNum == 0){
                        _this.getCode = '获取验证码';
                    }
                }, 1000);
              }else{
                _this.$api.showTip(result.data.msg);
              }
            })
        },
		getPassword(curpwd) {
			if (curpwd.indexOf('[#@$]') !== -1) {
				curpwd = curpwd.substring(5);

				try {
					let aesPwd = $api.aesDecrypt(curpwd);

					if (aesPwd != '') {
						curpwd = aesPwd;
					}
				} catch (es) {}
			}

			return curpwd;
		},

		handleLoginSuccess(userData, loginParams) {
			try {
				const expires = userData && userData.expires ? parseInt(userData.expires) : 10;
				const handleModifyPwd = () => {
					if (this.$config.isForceChangePassword == '1' && userData.initstatus == '0') {
						$api.navigateTo('/pages/gw-DSM/login/resetPwd');
					} else {
						this.handleLoginStorage(userData, loginParams);
					}
				};

				if (expires < 5) {
					const msg = `您的密码还有${expires}天过期，请及时更新密码。`;

					$api.showModalWithCloseButton(`您的密码还有${expires}天过期，请及时更新密码。`, () => {
						handleModifyPwd();
					});
				} else {
					this.handleLoginStorage(userData, loginParams);
				}
			} catch (e) {
				console.log(e);
				$api.showModalWithCloseButton('程序异常');
				this.loading = false;
				this.isSubmit = false;
			}
		},

		handleLoginStorage(userData, loginParams) {
			const lastUser = uni.getStorageSync('FRAMEWORK_FORCE_LOGOUT_USER');

			if (!lastUser || lastUser !== userData.ly_id) {
				loginTool.clearLastUserStorage();
			}

			userData.ly_id = userData.userid;
			userData.ly_loginname = userData.username;
			_self.$api.setUserInfo(userData);
			uni.switchTab({
				url: '../../framework/workflow/workflowList'
			});
		},

		// 处理登录异常
		handleLoginUnSuccess(result, username) {
			let errnums = result.data.errnums ? parseInt(result.data.errnums) : 0;
			if (errnums == '0') {
				$api.showModalWithCloseButton(`登录失败，请检查账号或密码！`);
			} else {
				$api.showModalWithCloseButton(`${result.message},您还有${errnums}次重试密码的机会`);
			}
		}
	},
	computed: {
		isOk() {
			if (this.password.length && this.username.length && this.protocol) {
				return true;
			} else {
				return false;
			}
		},
        isOk2() {
        	if (this.mobile.length && this.verificationCode.length) {
        		return true;
        	} else {
        		return false;
        	}
        }
	}
};
</script>

<style lang="scss">
page {
	background: #fff;
}
.loginBtn {
	border: 0;
	height: 80upx;
	line-height: 80upx;
	border-radius: 16upx;
	font-size: 32upx;
}
.loginBtn:after {
	border: 0;
	height: 80upx;
	line-height: 80upx;
	border-radius: 50upx;
}

.login-wrapper {
	width: 100%;
	height: 100%;

	background-size: cover;
	display: flex;
	align-items: center;
	// position: absolute;
	z-index: 1;
}

.main {
	// background-color: #fff;
	border-radius: 30upx 30upx 0 0;
	position: absolute;
	top: -50upx;
	position: relative;
	width: 100%;
	padding: 0 20px 20px;
    margin: 50px 20px;
    border-radius: 6px;

	&-logo {
		width: 100%;
		height: 67rpx;
		display: flex;
		flex-wrap: nowrap;
		align-items: center;

		image {
			width: 294rpx;
			height: 67rpx;
			flex-shrink: 0;
		}
	}
}
.opacity_05 {
	/* opacity: 0.5; */
    background-color: #D6D8DC !important;
}

.loginView {
	position: relative;
	width: 100%;
	display: flex;
	flex: 1;
	flex-direction: column;
	margin-top: 120rpx;

	.input-view {
		display: flex;
		/* border-bottom: 1px solid #e0e0e0; */
		width: 100%;
		/* padding-bottom: 30rpx; */
		margin-top: 25rpx;
		box-sizing: border-box;
        background: #F7F7F7;
        border-radius: 4px;
        height: 48px;
	}

	.input {
		width: 100%;
		height: 100%;
		line-height: 50rpx;
		flex-grow: 1;
		font-size: 32rpx;
        border-radius: 4px;
        padding-left: 10px;
		// font-weight: bold ;
		// color:#DDDDDD ;
	}
    [class*=" icon-"], [class^=icon-]{
        line-height: 45px !important;
        margin-right: 5px;
    }
	.input .input-placeholder {
		color: #ada8a8;
		font-weight: 100;
        line-height: 50px;
        font-size: 28upx;
	}

	.icon-guanbi {
		line-height: 50rpx;
		display: inline-block;
		padding-left: 15rpx;
	}

	.button-view {
		width: 100%;
		margin-top: 16rpx;
		box-sizing: border-box;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.protocol {
		margin-top: 20upx;
		font-family: PingFang-SC-Medium;
		font-size: 28upx;
		color: #999999;
		letter-spacing: 0;
		& > label {
			display: flex;
			align-items: center;
		}
		.protocol_b {
			.uni-checkbox-input {
				border-radius: 50% !important ;
			}
		}
		.select {
			width: 28upx;
			height: 28upx;
			border: 1px solid #a2a2a2;
			border-radius: 50%;
			position: relative;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-right: 20upx;
		}
		.selectb {
			&::after {
				content: '';
				display: block;
				width: 16upx;
				height: 16upx;
				background: #a2a2a2;
				border-radius: 50%;
			}
		}
	}

	.text-view {
		margin-top: 80rpx;
		display: flex;
		justify-content: center;

		text {
			font-size: 32rpx;
		}
	}
}

.valid-img {
	width: 300rpx;
	height: 80rpx;
	overflow: hidden;
	margin-left: 30rpx;
	background: #efefef;

	image {
		width: 200rpx;
		height: 80rpx;
	}
}
.remember {
	display: block;
	text-align: right;
	// margin-top: 20upx;
}
.remember1 {
	position: absolute;
	text-align: left;
}

.valid-wrapper {
	display: flex;
	align-items: flex-end;
}
.img_background {
	display: block;
	z-index: 0;
	position: fixed;
	top: 0;
	left: 0;
	width: 100vw;
}
.header {
	position: absolute;
	top: 100upx;
	left: 60upx;
	& view:nth-child(1) {
		font-size: 72upx;
		color: #333333;
		font-weight: bold;
		font-family: PingFangSC-Medium;
	}
	& view:nth-child(2) {
		font-weight: bold;
		font-family: PingFangSC-Medium;
		font-size: 36rpx;
		color: #98999a;
		letter-spacing: 0;
	}
}

.main-login-title{
    position: absolute;
    right: 0;
    width: 100%;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.login-title-left{
    position: absolute;
    left: 0;
    top: 0;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    border-radius: 6px 0 0 0;
}
.title-left-t{
    background: #fff;
    border-radius: 0 30px 0 0;
    uni-text{
        font-weight: bold;
    }
}
.title-left-f{
    border-radius: 0 0 30px 0;
    color: #B4B4B4;
    background: #F5F5F5;
}
.login-title-right{
    position: absolute;
    right: 0;
    top: 0;
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    border-radius: 0 6px 0 0;
}
.title-right-t{
    border-radius: 0 0 0 30px;
    color: #B4B4B4;
    background: #F5F5F5;
}
.title-right-f{
    border-radius: 30px 0 0 0;
    background: #fff;
    uni-text{
        font-weight: bold;
    }
}
</style>
